package com.book.web.controller.app;

import cn.hutool.core.util.DesensitizedUtil;
import com.book.common.annotation.RateLimiter;
import com.book.common.annotation.RepeatSubmit;
import com.book.common.constant.Constants;
import com.book.common.core.controller.BaseController;
import com.book.common.core.domain.AjaxResult;
import com.book.common.core.domain.entity.AppUser;
import com.book.common.core.domain.model.AppLoginBody;
import com.book.common.enums.LimitType;
import com.book.common.utils.SecurityUtils;
import com.book.common.utils.StringUtils;
import com.book.framework.web.service.AppLoginService;
import com.book.framework.web.service.AppPermissionService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.Set;

/**
 * @ClassName AppLoginController * @Description TODO
 * @Author 无BUG
 * @Date 15:09 2024/8/20 020
 * @Version 1.0
 **/
@Api(tags = "登录")
@RestController
public class AppLoginController extends BaseController {

    private final AppLoginService loginService;

    private final AppPermissionService permissionService;


    public AppLoginController(AppLoginService loginService, AppPermissionService permissionService) {
        this.loginService = loginService;
        this.permissionService = permissionService;
    }

    /**
     * 登录方法
     *
     * @param loginBody 登录信息
     * @return 结果
     */
    @ApiOperation(value = "App登录")
    @RepeatSubmit
    @PostMapping("/appLogin")
    public AjaxResult appLogin(@RequestBody AppLoginBody loginBody)
    {
        AjaxResult ajax = AjaxResult.success();
        // 生成令牌
        String token = loginService.login(loginBody.getUsername(), loginBody.getPassword());
        ajax.put(Constants.TOKEN, token);
        return ajax;
    }


    /**
     * 获取用户信息
     *
     * @return 用户信息
     */
    @ApiOperation(value = "App获取用户信息")
    @GetMapping("/app/getInfo")
    @RateLimiter(count = 60,limitType = LimitType.IP)
    public AjaxResult appGetInfo()
    {
        AppUser appUser = SecurityUtils.getAppLoginUser().getUser();
        //手机号进行脱敏
        if(StringUtils.isNotEmpty(appUser.getPhone())){
            appUser.setPhone(DesensitizedUtil.mobilePhone(appUser.getPhone()));
        }
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(appUser);
        AjaxResult ajax = AjaxResult.success();
        ajax.put("user", appUser);
        ajax.put("permissions", permissions);
        return ajax;
    }
}
